package com.gofun.report.util;

import java.io.IOException;

import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gofun.common.aop.RedisService;
import com.gofun.common.util.HttpClient;

public class WxSendMsg {
	public final static String WEIXIN_TOKEN = "weixin_token";
	public final static String APPID = "wxcf53702f0700cb52";
	public final static String SECRET = "1c62d2f0cdb1e5412088a79375f634ba";
	

	public static void sendTo(String content, String... openids){
		String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+getToken();
		
		
		try {
			for(String openid : openids){
				String text = "{\"touser\":\""+openid+"\",\"msgtype\":\"text\",\"text\":{\"content\":\""+content+"\"}}";
				String result = HttpClient.postBody(url, text);
//				System.out.println(result);
			}
		
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static String getToken() {
		RedisService redisService = (RedisService) SpringContextUtil.getBean("redisService");
		try {
			String token = (String) redisService.get(WEIXIN_TOKEN);
			if(token == null){
				String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APPID+"&secret="+SECRET;
				String tokenResult = HttpClient.doGet(tokenUrl);
				JSONObject tokenJson = JSON.parseObject(tokenResult);
				token = tokenJson.getString("access_token");
				int expires = tokenJson.getIntValue("expires_in");
				if(token != null && !"".equals(token)){
//					过期时间减去1000s   总共7200s
					redisService.set(WEIXIN_TOKEN, token, expires-1000);
				}	
			}
			
			return token;
		} catch (IOException e) {
			
		}
		return null;
	}
	
	
}
